package com.rocky.study.generic;



public class GenericMethodDemo1 {

    static class Pair<U,V> {
        U first;
        V second;

        public Pair(U first, V second) {
            this.first = first;
            this.second = second;
        }

        public U getFirst() {
            return first;
        }

        public void setFirst(U first) {
            this.first = first;
        }

        public V getSecond() {
            return second;
        }

        public void setSecond(V second) {
            this.second = second;
        }

        @Override
        public String toString() {
            return "Pair{" +
                    "first=" + first +
                    ", second=" + second +
                    '}';
        }
    }

    /**U必须是Number的子类,
     * V也必须是Number的子类,
     * 继承了泛型类Pair
     * */
    static class NumberPair<U extends Number,V extends Number> extends Pair<U,V> {

        public NumberPair(U first, V second) {
            super(first, second);
        }

        public double sum() {
            return getFirst().doubleValue() + getSecond().doubleValue();
        }
    }

    public static <U,V> Pair<U,V> makePair(U first, V second) {
        Pair<U,V> pair = new Pair<>(first, second);
        return pair;
    }

    public static void main(String[] args) {
        // 与泛型类不同,调用方法时一般并不需要特意指定类型参数的实际类型,比如调用makePair
        Pair<String,Integer> pair = makePair("color",2);
        System.out.println(pair.toString());
        // 限定类型后,如果类型使用错误,编译器会提示。指定边界后,类型擦除时就不会转换为Object了,而是会转换为它的边界类型
//        NumberPair<Integer,String> numberPair = new NumberPair<>(12,12.5);
        NumberPair<Integer,Double> numberPair = new NumberPair<>(12,12.5);
        double sum = numberPair.sum();
        System.out.println(sum);
    }
}
